import request from '../request.js'
import common from "../common.js"
import file from './file.js'
// #ifdef H5
let jweixin = require('jweixin-module')
// #endif
// #ifdef APP-PLUS|MP-WEIXIN|MP-TOUTIAO
const recorderManager = uni.getRecorderManager()
// #endif

/* 2022.08.11 兼容了微信公众号
2022.09.20 兼容了微信小程序 */

let record = {}

/**
 * 判断是否授权录音功能
 * @date 2022-08-11
 */
record.isAuth = function() {
	return new Promise((resolve, reject) => {
		// #ifdef H5
		// 公众号
		if (common.userAgent() == 'weixin') {
			// 微信公众号没有官方方案，采用缓存的办法执行 true--有权限 false--没有权限
			let is_auth_record = uni.getStorageSync('is_auth_record')
			resolve(is_auth_record)
		}
		// #endif

		// #ifdef MP-WEIXIN|MP-TOUTIAO
		uni.getSetting({
			success(res) {
				// 没有录音权限
				if (!res.authSetting['scope.record']) {
					// 提前向用户发起授权请求
					uni.authorize({
						scope: 'scope.record',
						success(res) {
							console.log('authorizeSuccess', res)
							// 刚授权成功返回false，为了重新发起录音
							resolve(false)
						},
						fail(res) {
							console.log('authorizeFail', res)
							uni.showModal({
								title: "您已拒绝录音权限",
								content: "是否进入权限管理，调整授权？",
								success(res) {
									if (res.confirm) {
										uni.openSetting({
											success(res) {
												resolve(false)
											}
										})
									} else {
										resolve(false)
									}
								}
							})
						},
						complete(res) {
							// console.log('authorizeComplete', res)
						}
					})
				} else {
					resolve(true)
				}
			}
		})
		// #endif
	})
}

/**
 * 开始录音，单条录音
 * @date 2022-08-10
 */
record.record = function() {
	return new Promise((resolve, reject) => {
		// #ifdef H5
		// 公众号
		if (common.userAgent() == 'weixin') {
			// 开始录音接口
			jweixin.startRecord({
				success(res) {
					console.log('wxStartRecordSuccess', res)
					resolve(res)
				},
				fail(res) {
					console.log('wxStartRecordFail', res)
					reject(res)
				},
				complete(res) {
					// console.log('wxStartRecordComplete', res)
					// 弹出授权点击否走complete方法,{errMsg:"startRecord:cancel"}
					// 授权点击否
					if (res.errMsg == "startRecord:cancel") {
						reject(res)
					}
				}
			})
		}
		// #endif

		// #ifdef MP-WEIXIN|APP-PLUS|MP-TOUTIAO
		recorderManager.start({
			// #ifdef APP-PLUS|MP-WEIXIN
			// 1分钟
			duration: 60000,
			format: 'mp3',
			// #endif

			success(res) {
				console.log('recorderManagerStartSuccess', res)
				resolve(res)
			},
			fail(res) {
				console.log('recorderManagerStartFail', res)
				reject(res)
			},
			complete(res) {
				console.log('recorderManagerStartComplete', res)
			}
		})
		// #endif
	})
}

/**
 * 结束录音，单条录音
 * @param {int} isUploadVoice 是否需要上传录音到云端 false--不需要 true--需要
 * @date 2022-08-10
 */
record.stopRecord = function(isUploadVoice = true) {
	return new Promise((resolve, reject) => {

		// #ifdef H5
		// 公众号
		if (common.userAgent() == 'weixin') {
			// 停止录音接口
			jweixin.stopRecord({
				success: (res) => {
					console.log('wxStopRecordSuccess', res)
					if (isUploadVoice) {
						this.uploadVoice(res.localId).then(res => {
							console.log(res)
							resolve(res.url)
						}).catch(res => {
							reject(res)
						})
					} else {
						resolve(res)
					}
				},
				fail: (res) => {
					console.log('wxStopRecordFail', res)
					reject(res)
				},
				complete(res) {
					console.log('wxStopRecordComplete', res)
				}
			})
		}
		// #endif

		// #ifdef APP-PLUS|MP-WEIXIN|MP-TOUTIAO
		recorderManager.stop()
		resolve('')
		// #endif
	})
}


/**
 * 微信上传录音，返回服务端ID，上传到OSS
 * 2022-08-10
 */
record.uploadVoice = function(localId) {
	return new Promise((resolve, reject) => {
		// 上传语音接口
		jweixin.uploadVoice({
			// 需要上传的音频的本地ID，由 stopRecord 接口获得
			localId: localId,
			// 默认为1，显示进度提示
			isShowProgressTips: 0,
			success: (res) => {
				console.log('wxUploadVoiceSuccess', res)
				// 返回音频的服务器端ID
				let serverId = res.serverId

				// 将前台录音文件的MediaId（即serverId）文件下载到本地并上传至OSS
				request.getData('base/wechat/api/Media/getRecordMediaToOss', {
					media_id: serverId
				}).then(res => {
					if (res.code == 0) {
						resolve({
							url: res.data.oss_url
						})
					} else {
						reject(res)
					}
				})
			},
			fail: (res) => {
				console.log('wxUploadVoiceFail', res)
				reject(res)
			},
			complete(res) {
				console.log('wxUploadVoiceComplete', res)
			}
		})
	})
}

/**
 * MP-WEIXIN 平台 上传录音文件到OSS
 * @param {string} tempFilePath 录音文件的临时路径 例如：(微信小程序)wxfile://tmp_b93d40bd1e3d53bcbdf7b88e05924f96.mp3
 * @param {boolean} isOriginalName false--随机文件名  true--原文件名
 * @date 2022-05-07
 */
record.uploadRecordFile = function(tempFilePath, isOriginalName = false) {
	return new Promise((resolve, reject) => {
		console.log(tempFilePath)
		
		/* 需要上传的文件数组 */
		let fileQueue = []

		let name

		// 获取源文件名称
		let pos = tempFilePath.lastIndexOf('/')
		if (pos != -1) {
			name = tempFilePath.substring(pos + 1)
		}

		fileQueue.push({
			// 原文件名
			name: name,
			// 后缀
			ext: common.getSuffix(name),
			// 路径
			path: tempFilePath,
			// 文件
			// file: tempFilePath
		})

		// 上传录音文件
		file.uploadFiles(fileQueue, [], 'audio').then(res => {
			uni.hideLoading()
			resolve(res)
		}).catch(err => {
			uni.hideLoading()
			reject(err)
		})
	})
}

export default record